package com.ambition.mallchat.common.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ambition.mallchat.common.constant.RedisKey;
import com.ambition.mallchat.common.user.domain.entity.User;
import com.ambition.mallchat.common.user.service.LoginService;
import com.ambition.mallchat.common.utils.JwtUtils;
import com.ambition.mallchat.common.utils.RedisUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: mallchat-learnning
 * @ClassName LoginServiceImpl
 * @description:
 * @author: oldTea
 * @create: 2023-10-29 10:46
 * @Version 1.0
 **/
@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRE_TIME = 3;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(User user) {
        return null;
    }

    @Override
    public boolean verify(String token) {
        return false;
    }

    @Override
    public void renewalTokenIfNecessary(String token) {

    }

    @Override
    public String login(Long uid) {
        String token = jwtUtils.createToken(uid);
        RedisUtils.set(getUserTokenKey(uid),token, TOKEN_EXPIRE_TIME);
        return token;
    }

    @Override
    public Long getValidUid(String oldToken) {
        String s = "sdsad";
        Long uid = jwtUtils.getUidOrNull(oldToken);
        if(ObjectUtil.isNull(uid)){
            return null;
        }
        String newToken = getUserTokenKey(uid);
        if(StringUtils.isBlank(newToken)){
            return null;
        }
        return ObjectUtil.equal(oldToken,newToken)?uid:null;
    }
    public String getUserTokenKey(Long uid){
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING,uid);
    }
}